let express = require('express');
let cors = require('cors');
let connection = require('./api/dataBase');
const { verifyToken } = require('./api/jwt');
const Result = require('./api/result');
let app = express();

// 解析body
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.use(cors());

app.all('*', function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', '*');
  res.setHeader('Access-Control-Allow-Methods', '*');
  next();
});

// 请求拦截，验证token
app.use((req, res, next) => {
  let [url] = req.url.split('?');
  if (!url.includes('public') && req.method !== 'OPTIONS') {
    // 过滤prefight和白名单
    try {
      if (!req.headers.authorization) return new Result(res, 401).fail(200);
      let account = verifyToken(req.headers.authorization);
      if (account.exp * 1000 < Date.now()) {
        return new Result(res).fail(401);
      }
      const sql = `select * from account where email="${account.email}" and password = "${account.password}"`;
      connection.query(sql, (err, data) => {
        if (err) {
          return new Result(res, 1200).fail();
        }
        //   获取不到数据
        if (data.length === 0) {
          return new Result(res).fail(404);
        }
        next();
      });
    } catch (error) {
      return new Result(res, 1200).fail(500);
    }
  } else {
    next();
  }
});

// // 模块
let modules = ['account', 'article', 'comment', 'action', 'like', 'attention'];
for (let i = 0; i < modules.length; i++) {
  let m = require(`./api/api/${modules[i]}`);
  app.use(`/aptw/${modules[i]}`, m);
}

//监听端口
app.listen(8902, function () {
  console.log('success listen at port:8902......');
});
